<template>
    <a-spin :spinning="confirmLoading">

      <!-- {{detailDataSource}} -->

        <h2>编辑单位</h2>

      <j-form-container :disabled="formDisabled">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="分组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitCode">
                  <!-- v-model="detailDataSource.cyEmissionUnit.parentName" 将查询到的详情数据绑定到该控件上 -->
                  <!-- @change="setGroupIdAndName" 如果下拉框的内容改变，则将 detailDataSource.cyEmissionUnit.parentName和  detailDataSource.cyEmissionUnit.parentId 重新进行赋值-->
                <div v-if="detailFlag == 0">
                  <a-select style="width: 180px; margin-left:20px" placeholder="请选择" @change="setGroupIdAndName" v-model="detailDataSource.cyEmissionUnit.parentName"  optionFilterProp="label" showSearch allowClear>
                    <a-select-option v-for="item in unitGroupList" :key="item.id" :label="item.unitCode" :value="item.id">{{item.groupName}}</a-select-option>
                  </a-select>  
                </div>
                <div v-else>
                  <a-input style="width: 180px; margin-left:20px" v-model="detailDataSource.cyEmissionUnit.parentName" placeholder="请输入单位名称"  ></a-input>
                </div>
              </a-form-model-item>
            </a-col>
  
            <a-col :span="24">
              <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitName">
                <a-input @change="setUnitCode" style="width: 180px; margin-left:20px" v-model="detailDataSource.cyEmissionUnit.unitCode" placeholder="请输入单位名称"  ></a-input>
              </a-form-model-item>
            </a-col>
  
            <a-col :span="24">
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="parentId">
                <div style="margin-top:20px;margin-bottom: 20px; font-weight: bold; font-size: 20px">
                  单位换算
                </div>
  
                <!-- 展示出对象中包含的所有的正向转换对象 -->
            <div v-for="(item,SourceIndex) in forwardList" :key="SourceIndex"  style= "background-color: #ffffff;margin-bottom: 20px;">

              <div style="display:flex">

                <div v-if="detailFlag == 1 && (item.sourceUnit == null || item.sourceUnit == '')   " style="min-width: 40px;" >
                      1 - =
                    </div>

                    <div v-if="detailFlag == 0 && (detailDataSource.cyEmissionUnit.unitCode == null || detailDataSource.cyEmissionUnit.unitCode == '') " style="min-width: 40px;" >
                      1 - =
                    </div>
                    
                    <div v-if="detailFlag == 1 && item.sourceUnit != null && item.sourceUnit != '' " style="min-width: 70px;" >
                      <!-- 1 {{detailDataSource.cyEmissionUnit.unitCode}} = -->
                      1 {{item.sourceUnit}} =
                    </div> 

                    <div v-if="detailFlag == 0 && detailDataSource.cyEmissionUnit.unitCode != null && detailDataSource.cyEmissionUnit.unitCode != '' " style="min-width: 70px;" >
                      <!-- 1 {{detailDataSource.cyEmissionUnit.unitCode}} = -->
                      1 {{item.sourceUnit}} =
                    </div> 
                  
                  <a-input v-model="item.value"  placeholder="转换值" style="width: 180px; margin-left:10px;margin-top:4px" @change="setConvertValue(item,SourceIndex)" ></a-input>

                  <div v-if="detailFlag == 0">
                    <a-select style="width: 180px; margin-left:20px" placeholder="请选择" @change="setTargetUnitAndId($event,item,SourceIndex)" v-model="item.targetUnit"   optionFilterProp="label" showSearch allowClear>
                    <a-select-option v-for="UnitItem in unitList" :key="UnitItem.id" :label="UnitItem.unitCode" :value="UnitItem.id">{{UnitItem.unitCode}}</a-select-option>
                  </a-select> 
                </div>

                <div v-else>
                  <a-input style="width: 180px; margin-left:20px" v-model="item.targetUnit" placeholder="请输入单位名称"  ></a-input>
                </div>

                  <!-- 删除转换对象（同时删除正向和对应的反向转换对象） -->
                  <a-button v-show="detailFlag == 0" style="margin-left:20px;margin-top:4px" type="primary" @click="deleteConvertItem(SourceIndex)" >删除</a-button>
              </div>  

              <!-- 转换对象一组一组展示的效果 -->
              <!-- 由于正向转换对象和反向转换对象下标是对应的，所有可以通过相同下标来进行成组展示的效果 -->
                <!-- 展示出对象中包含的所有的反向转换对象 -->
                <div style="margin-bottom:20px">
                    <span style="min-width: 40px;"  v-if="contraryList[SourceIndex].sourceUnit == null || contraryList[SourceIndex].sourceUnit == ''">
                      1 - =
                    </span>

                    <span  v-else style="width:200px; min-width: 40px;">
                    1 {{contraryList[SourceIndex].sourceUnit}} =
                    </span>

                  <a-input v-model="contraryList[SourceIndex].value"  placeholder="转换值" style="width: 180px; margin-left:15px"></a-input>

                  <span v-if="contraryList[SourceIndex].targetUnit == null || contraryList[SourceIndex].targetUnit == ''" style="margin-left:20px"  >
                      1 - 
                    </span>

                  <span v-else style="margin-left:20px">
                    {{contraryList[SourceIndex].targetUnit}} 
                  </span>
                </div>
            </div>
  
             <!-- 展示出对象中包含的所有的反向转换对象 -->
            <!-- <div v-for="(contraryItem,index) in contraryList" >
  
              <div style="margin-bottom:20px">
  
                  <span style="min-width: 40px;"  v-if="contraryItem.sourceUnit == null || contraryItem.sourceUnit == ''">
                    1 - =
                  </span>
  
                  <span  v-else style="width:200px; min-width: 40px;">
                  1 {{contraryItem.sourceUnit}} =
                  </span>
  
                <a-input v-model="contraryItem.value"  placeholder="转换值" style="width: 180px; margin-left:5px"></a-input>
  
                <span v-if="contraryItem.targetUnit == null || contraryItem.targetUnit == ''">
                    1 - 
                  </span>
  
                <span v-else>
                  {{contraryItem.targetUnit}} 
                </span>
              </div>
            </div> -->
  
      <div v-show="detailFlag == 0" style="color:blue;cursor: pointer;" @click="addRow()"  >
          添加单位换算
      </div>
  
  
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
    </a-spin>
  </template>
  
  <script>
  
    import { httpAction, getAction } from '@/api/manage'
    import { validateDuplicateValue } from '@/utils/util'
  
    export default {
      name: 'CyEmissionUnitForm',
      components: {
      },
      props: {
        // 被编辑对象的数据源（由父组件传递过来）
        detailDataSource:{},
        // 编辑与详情的区分标致
        detailFlag:null,
        // 正向单位转换数组
        forwardList:[],
        // 反向单位转换数组
        contraryList:[],
        //表单禁用
        disabled: {
          type: Boolean,
          default: false,
          required: false,
        }
      },
      data () {
        return {
          model:{
            parentName:'',
            parentId:'',
            unitConvertList:[],
           },
          labelCol: {
            xs: { span: 24 },
            sm: { span: 5 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
          },
          confirmLoading: false,
          validatorRules: {
          },
          url: {
            add: "/emission/factor/cyEmissionUnit/add",
            edit: "/emission/factor/cyEmissionUnit/edit",
            queryById: "/CyEmissionUnit/cyEmissionUnit/queryById",
            unitGroup:"/CyFactorUnitGroup/cyFactorUnitGroup/list",
            unitList: "/emission/factor/cyEmissionUnit/list",
          },
          contraryList:[],
          forwardList:[],
          // 单位分组数组
          unitGroupList:[],
          // 单位数组
          unitList:[],
        }
      },
      computed: {
        formDisabled(){
          return this.disabled
        },
      },
      created () {
         //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        // 查询单位分组
        this.searchGroup();
        // 查询单位
        this.searchUnit();
        // 区分数据源对象中的正反向数组方法
        this.distinguishList();

      },
      methods: {
        submitqqqq(){
        this.$emit('getAllConvert',this.forwardList,this.contraryList)
        },
        // 分组改变时，同时改变分组名称和分组id
        setGroupIdAndName(selectedObj){
          let theIndex =  this.unitGroupList.findIndex(ele=>ele.id == selectedObj)
          let theObj = this.unitGroupList[theIndex];
          
          // 更新分组名称和分组id
          this.detailDataSource.cyEmissionUnit.parentName = theObj.groupName
          this.detailDataSource.cyEmissionUnit.parentId = theObj.id
        },
        // 正向单位转化对象的 目标单位改变时，同时改变目标单位名称和 目标单位id
        setTargetUnitAndId(selectedObj,item,SourceIndex){
          let theIndex =  this.unitList.findIndex(ele=>ele.id == selectedObj)
          let theObj = this.unitList[theIndex];
  
          // 将主体对象的单位赋值给正向转换对象的来源单位名称
          item.sourceUnit = this.detailDataSource.cyEmissionUnit.unitCode;
          item.targetUnit = theObj.unitCode;
          item.targetUnitId = theObj.id;
  
          console.log(item);
  
          // 正向单位转换对象属性赋值后，同步给对应的反向转换对象属性赋值
          this.contraryList[SourceIndex].sourceUnit = item.targetUnit;
          this.contraryList[SourceIndex].unitId = item.targetUnitId;
          this.contraryList[SourceIndex].targetUnit = item.sourceUnit;
        },
       //正向单位转换对象中的转换值改变时，同时改变反向转换对象中的转换值（自动设置为正向的倒数）
      setConvertValue(item,SourceIndex){
        console.log(item.value)
        if(item.value!=null && item.value!=undefined && item.value!= 0){
          this.contraryList[SourceIndex].value = (1/item.value).toFixed(6)
        }
      },
        // 增加单位换算对象
        addRow(){
          // 增加时同步增加正向和反向的
          this.forwardList.push({sourceUnit: this.detailDataSource.cyEmissionUnit.unitCode,sourceUnitId:'',value:'',targetUnit:'',targetUnitId:'',type:"1"});
          this.contraryList.push({sourceUnit: '',unitId:'',value:'',targetUnit:this.detailDataSource.cyEmissionUnit.unitCode,targetUnitId:'',type:"2"})
          console.log(this.modelDefault)
        },
        //单位分组分页列表查询
        searchGroup(){
          getAction(this.url.unitGroup).then(res=>{
            this.unitGroupList = res.result.records
        })
        },
        //查询单位
        searchUnit(){
          getAction(this.url.unitList,{pageSize:-1}).then(res=>{
            this.unitList = res.result.records
        }) 
        },
        add () {
          this.edit(this.modelDefault);
          
        },
        edit (record) {
          this.model = Object.assign({}, record);
          this.visible = true;
        },
        //确认正反向转换数组
        distinguishList(){
            // 对数组进行初始化操作
            this.forwardList = [];
            this.contraryList = [];
            // 因为返回的转换数组为混合数组cyEmissionUnitConvert，所以区分好正向反向转换对象
            if(this.detailDataSource.cyEmissionUnitConvert != null && this.detailDataSource.cyEmissionUnitConvert.length > 0){
                for(let i=0;i< this.detailDataSource.cyEmissionUnitConvert.length;i++){
                    if(this.detailDataSource.cyEmissionUnitConvert[i].type == "1"){
                        this.forwardList.push(this.detailDataSource.cyEmissionUnitConvert[i])
                    }else{
                        this.contraryList.push(this.detailDataSource.cyEmissionUnitConvert[i])
                    }
                }
            }else{
              // 如果源转换对象数组为空，则将正向和反向数组都设置为空
                this.forwardList = [];
                this.contraryList = [];
            }
        },
        //删除转换对象
        deleteConvertItem(index){
            this.forwardList.splice(index,1)
            this.contraryList.splice(index,1)
        },
        // 当单位名称改变时，改变所有正向和反向单位转换对象中关联的单位名称
        setUnitCode(){

          for(let i=0;i< this.forwardList.length;i++){
            this.forwardList[i].sourceUnit = this.detailDataSource.cyEmissionUnit.unitCode
            //同时将目标单位清空，因为可能会造成数据不一致，所以情况需要重新选
            this.forwardList[i].targetUnit = null;
          }

          for(let i=0;i< this.forwardList.length;i++){
            this.contraryList[i].targetUnit = this.detailDataSource.cyEmissionUnit.unitCode
            //同时将目标单位清空，因为可能会造成数据不一致，所以情况需要重新选
            this.contraryList[i].sourceUnit = null;
          }
        },
        submitForm () {
  
          if(this.model.unitConvertList == undefined){
            this.model.unitConvertList = [];
          }

          for(let i=0;i<this.contraryList.length;i++){
            this.model.unitConvertList.push(this.contraryList[i]);
          }
  
          for(let i=0;i<this.forwardList.length;i++){
            this.model.unitConvertList.push(this.forwardList[i]);
          }
          console.log(this.model);
  
          const that = this;
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.confirmLoading = true;
              let httpurl = '';
              let method = '';
              if(!this.model.id){
                httpurl+=this.url.add;
                method = 'post';
              }else{
                httpurl+=this.url.edit;
                 method = 'put';
              }
              httpAction(httpurl,this.model,method).then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  that.$emit('ok');
                }else{
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
              })
            }
          })
        },
      }
    }
  </script>